import { Navigate, Route, Routes, useNavigate } from "react-router-dom";
import ProLayout from "./components/layout";
import { routersData } from "./router";

import Login from "@/pages/login";

import "./App.scss";
import { useAppDispatch } from "./store";
import { get_user_info } from "./store/slice/app";
import EventBus from "./utils/events";
import { useEffect } from "react";
import { notification } from "antd";
import { logout } from "./api/common";

const openNotification = (msg: string) => {
  notification.error({
    message: "发生错误",
    description: `错误信息： ${msg}`,
  });
};

function App() {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  EventBus.on("global_not_login", function (msg) {
    navigate("/login");
  });

  // 没有权限的处理
  EventBus.on("global_error_auth", function (msg) {
    openNotification(msg);
    logout().then(() => {
      navigate("/login");
    });
  });
  // 全局错误处理
  EventBus.on("global_requet_error", function (msg) {
    openNotification(msg);
  })
  useEffect(() => {
    dispatch(get_user_info());
  }, []); // eslint-disable-line
  const childrenRoutes = routersData.map((item) => {
    return (
      <Route
        key={item.path}
        path={item.path}
        element={<item.element />}
      ></Route>
    );
  });
  return (
    <Routes>
      <Route path="/" element={<Navigate to={"/home"}></Navigate>}></Route>
      <Route path={"/login"} element={<Login />}></Route>
      <Route element={<ProLayout />}>{childrenRoutes}</Route>
    </Routes>
  );
}

export default App;
